package com.cskaoyan.gateway.controller.user;

import com.alibaba.fastjson.JSON;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.ILoginService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.KaptchaCodeRequest;
import com.mall.user.dto.KaptchaCodeResponse;
import com.mall.user.dto.UserLoginRequest;
import com.mall.user.dto.UserLoginResponse;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: ZaiRiChangYe
 * @Date: 2020/5/11 20:42
 * @Description: 用户登陆中心控制层
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    @Reference(check = false)
    private IKaptchaService iKaptchaService;

    @Reference(check = false)
    private ILoginService loginService;

    /**
     * 用户登录接口
     */
    @PostMapping("/login")
    @Anoymous
    public ResponseData login(@RequestBody Map<String,String> map, HttpServletRequest request, HttpServletResponse response){
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");


        // 验证验证码 -- 同注册中的验证验证码逻辑一致
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse kaptchaCodeResponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        String code = kaptchaCodeResponse.getImageCode();

        if (!code.equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }

        // 验证用户名和密码
        UserLoginRequest userLoginRequest = new UserLoginRequest();
        userLoginRequest.setUserName(userName);
        userLoginRequest.setPassword(userPwd);
        UserLoginResponse userLoginResponse = loginService.login(userLoginRequest);

        // 说明验证用户名和密码成功了
        if (userLoginResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            // 往response中塞入cookie信息
            Cookie cookie = CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN, userLoginResponse.getToken(), "/", 24 * 60 * 60);
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            return new ResponseUtil<>().setData(userLoginResponse);
        }
        return new ResponseUtil<>().setErrorMsg(userLoginResponse.getMsg());
    }

    /**
     * 验证用户登录接口
     */
    @GetMapping("/login")
    public ResponseData checkLogin(HttpServletRequest request, HttpServletResponse response){
        String userInfo = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        Object object = JSON.parse(userInfo);
        return new ResponseUtil<>().setData(object);
    }

    /**
     * 用户退出接口
     * 最重要是撤回cookie信息
     */
    @GetMapping("/loginOut")
    public ResponseData logOut(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            // 循環找出所需要的ACCESS_TOKEN，並銷毀即可
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(TokenIntercepter.ACCESS_TOKEN)){
                    cookie.setValue(null);       // 设置value为null即是销毁
                    cookie.setMaxAge(0);         // 让改cookie立即过期
                    cookie.setPath("/");
                    response.addCookie(cookie);  // 覆盖原来的cookie
                }
            }
        }
        return new ResponseUtil<>().setData(null);
    }

}
